package com.hjs.servlet.user;

import com.hjs.mapper.UsersMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author flamemaster
 * @date 2020/6/17
 **/
@WebServlet("/user/delete")
public class Delete extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        RequestUtil requestUtil = new RequestUtil(request, response);
        switch (requestUtil.getInt("deleteType")){
            case 1:
                deleteUser(requestUtil);
                break;
            case 2:
                deleteDepartment(requestUtil);
                break;
            case 3:
                deleteGrade(requestUtil);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + Integer.parseInt(request.getParameter("addType")));
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){

    }

    private void deleteUser(RequestUtil requestUtil){
        Mapper<UsersMapper> usersMapperMapper = new Mapper<>(UsersMapper.class);
        try {
            UsersMapper usersMapper = usersMapperMapper.getMapper();
            boolean result = usersMapper.deleteOneUsersById(requestUtil.getString("userID"));
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            requestUtil.responseWrite("{\"result\": false + }");
        }finally {
            usersMapperMapper.closeSession();
        }
    }
    private void deleteDepartment(RequestUtil requestUtil){
        Mapper<UsersMapper> usersMapperMapper = new Mapper<>(UsersMapper.class);
        try {
            UsersMapper usersMapper = usersMapperMapper.getMapper();
            boolean result = usersMapper.deleteOneDepartmentById(requestUtil.getInt("departmentID"));
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            requestUtil.responseWrite("{\"result\":false}");
        }finally {
            usersMapperMapper.closeSession();
        }
    }
    private void deleteGrade(RequestUtil requestUtil){
        Mapper<UsersMapper> usersMapperMapper = new Mapper<>(UsersMapper.class);
        try {
            UsersMapper usersMapper = usersMapperMapper.getMapper();
            boolean result = usersMapper.deleteOneRightGradeById(requestUtil.getInt("rightGradeID"));
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            requestUtil.responseWrite("{\"result\":false}");
        }finally {
            usersMapperMapper.closeSession();
        }
    }

}
